package com.bigtotoro.shuiyincamera;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;
import com.bigtotoro.shuiyincamera.fragment.FindFragment;
import com.bigtotoro.shuiyincamera.fragment.HomeFragment;
import com.bigtotoro.shuiyincamera.fragment.MyFragment;
import com.bigtotoro.shuiyincamera.util.MyUtils;
import com.bigtotoro.shuiyincamera.util.SharedPreferencesUtil;
import com.bigtotoro.shuiyincamera.util.StatusBarUtil;
import com.umeng.analytics.MobclickAgent;
import static com.bigtotoro.shuiyincamera.Constant.SP_XIEYI;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private LinearLayout btn_01,btn_02,btn_03;
//    private final String[] TAGS = { "home", "find","my"};
    private final String[] TAGS = { "home","my"};
//    private final Class<?>[] CLASSES = { HomeFragment.class, FindFragment.class,MyFragment.class};
    private final Class<?>[] CLASSES = { HomeFragment.class,MyFragment.class};
    private int position = 0;
    private Fragment mContent;
    private View item;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("SplashActivity", "MainActivity" + System.currentTimeMillis());
        setContentView(R.layout.activity_main);

        //设置状态栏隐藏，与StatusBarCompat.setStatusBarColor冲突
        StatusBarUtil.setTransparentForImageViewInFragment(MainActivity.this, null);
        StatusBarUtil.setDarkMode(MainActivity.this);

        initView();

    }

    private void initView() {
        int id = getIntent().getIntExtra("id", R.id.btn_01);
        btn_01 = findViewById(R.id.btn_01);btn_01.setOnClickListener(this);
        btn_02 = findViewById(R.id.btn_02);btn_02.setOnClickListener(this);
//        btn_03 = findViewById(R.id.btn_03);btn_03.setOnClickListener(this);
        updateTab(id);

        item = findViewById(R.id.item);
        //判断是否启动提示框
        if(SharedPreferencesUtil.getInstance(MainActivity.this).isSP(Constant.SP_XIEYI)){
            checkUpdate();
        }else{
            //弹出提示框
            item.post(new Runnable() {
                @Override
                public void run() {
                    showFirstInPopwindow();
                }
            });
        }
    }

    private PackageInfo info;
    private void checkUpdate() {
        item.postDelayed(new Runnable() {
            @Override
            public void run() {
                MyUtils.checkVersion(MainActivity.this,-1, new MyUtils.IntegerCallback() {
                    @Override
                    public void callback(int data) {
                        if (data == 2){  //有新版本
                            final AlertDialog builder = new AlertDialog.Builder(MainActivity.this)
                                    .setTitle("温馨提示").setMessage("当前应用有新版本，是否更新？").setCancelable(false).setPositiveButton("确定",
                                            new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    dialog.dismiss();
                                                    exitApp(); //点确定退出应用
                                                }
                                            })
//                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
////                                        @Override
////                                        public void onClick(DialogInterface dialog, int which) {
////                                            dialog.dismiss();
////                                        }
////                                    })
                                    .show();
                            //修改 确定取消 按钮的字体大小
                            builder.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.theme_color));
//                            builder.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.theme_color));

                        }
                    }
                });
            }
        },1500);
    }

    private int isCheckd = 0;
    private void showFirstInPopwindow() {
        View popView = View.inflate(MainActivity.this, R.layout.pop_item3, null);
        int width = getResources().getDisplayMetrics().widthPixels;
        int height = MyUtils.dp2px(200);
        final PopupWindow popWindow = new PopupWindow(popView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置同意在外点击消失
        CheckBox checkBox = popView.findViewById(R.id.check);
        checkBox.setChecked(true);

        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b){
                    isCheckd = 0;
                }else {
                    isCheckd = 1;
                }
            }
        });

        View.OnClickListener listener = new View.OnClickListener() {
            public void onClick(View v) {   //既然是清空，那不管有没有历史记录，最后都是变成没有历史记录的状态
                int i = v.getId();
                if (i == R.id.btn_submit) { //确定按钮
                    if(checkBox.isChecked()){
                        if (isCheckd == 0){
                            SharedPreferencesUtil.getInstance(MainActivity.this).putSP(SP_XIEYI, true);
                        }else if (isCheckd == 1){
                            SharedPreferencesUtil.getInstance(MainActivity.this).putSP(SP_XIEYI, false);
                        }
                        popWindow.dismiss();
                        checkUpdate();
                    }else{
                        Toast.makeText(MainActivity.this, R.string.check_xieyi, Toast.LENGTH_SHORT).show();
                    }
                } else if (i == R.id.txt_xieyi) { //跳转用户协议界面
                    startActivity(new Intent(MainActivity.this, XieyiActivity.class));
                }else if (i == R.id.btn_close) {
                    popWindow.dismiss();
                    exitApp();
                    //关闭app
                }
            }
        };

        popView.findViewById(R.id.btn_close).setOnClickListener(listener);
        popView.findViewById(R.id.txt_xieyi).setOnClickListener(listener);
        popView.findViewById(R.id.btn_submit).setOnClickListener(listener);
        popWindow.setClippingEnabled(false);

        boolean bb =  MyUtils.checkDeviceHasNavigationBar(MainActivity.this);
        int NavigationBarHeight = 0;
        if (bb){   //有虚拟键盘，需要减去虚拟键盘的高度，否则虚拟键盘会挡住底部
            NavigationBarHeight  = MyUtils.getNavigationBarHeight(MainActivity.this);
        }
        popWindow.showAtLocation(item, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, NavigationBarHeight);
        item.setFocusable(false);
        item.setFocusableInTouchMode(false);
    }

    private void exitApp() {
        this.finish();
    }

    public void togglePage(int position) {   //切换fragment页面
        this.position = position;
        if (position < 0 || position > TAGS.length) {
            Toast.makeText(this, "out... in togglePage.", Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        Fragment fragment = getSupportFragmentManager().findFragmentByTag(
                TAGS[position]);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if (mContent != null) {
            ft.detach(mContent);//分离fragment
        }
        if (fragment == null) {  //根据给定的name创建fragment实例
            fragment = Fragment.instantiate(this, CLASSES[position].getName());
            ft.add(R.id.content, fragment, TAGS[position]);
        } else {
            ft.attach(fragment);//绑定经过detach方法分离的fragment
        }
        mContent = fragment;
        ft.commit();
        getSupportFragmentManager().executePendingTransactions();
    }

    public void updateTab(int id) {  //更新底部导航栏状态
        switch (id) {
            case R.id.btn_01:
//                StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.theme_color));
                btn_01.setSelected(true);
                btn_02.setSelected(false);
//                btn_03.setSelected(false);
                togglePage(position = 0);
                break;
            case R.id.btn_02:
//                StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.theme_color));
                btn_01.setSelected(false);
                btn_02.setSelected(true);
//                btn_03.setSelected(false);
                togglePage(position = 1);
                break;
//            case R.id.btn_03:
//////                StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.theme_color));
////                btn_01.setSelected(false);
////                btn_02.setSelected(false);
////                btn_03.setSelected(true);
////                togglePage(position = 2);
////                break;
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_01:
            case R.id.btn_02:
//            case R.id.btn_03:
                updateTab(v.getId());
                break;
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("MainActivity");//统计页面
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MainActivity");//统计页面
        MobclickAgent.onPause(this);
    }
}
